// 1. 导入
// 2. 注册
// 3. 初始化
// 4. 导出

import VueRouter from 'vue-router'
import Vue from 'vue'
import auth from '@/utils/auth'

// 导入组件
// 路由懒加载方式
const Login = () => import('@/views/login')
const Layout = () => import('@/views/Layout')
const Home = () => import('@/views/home')
const Article = () => import('@/views/article')
const Publish = () => import('@/views/publish')

Vue.use(VueRouter)

const router = new VueRouter({
  // 路由规则配置
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      // 二级路由
      children: [
        { path: '/', component: Home },
        { path: '/article', component: Article },
        { path: '/publish', component: Publish }
      ]
    }
  ]
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const token = auth.getToken()
  if (!token && to.path !== '/login') {
    // 1. 如果未登录，访问的不是登录页面（访问后台页面），拦截到登录页面
    next('/login')
  } else {
    // 2. 其他情况一概放行
    next()
  }
})

export default router
